//
//  PingListViewController.m
//  MyYiJianKangApp
//
//  Created by 张国文 on 16/5/12.
//  Copyright © 2016年 hangzhouyijiyin. All rights reserved.
//

#import "PingListViewController.h"
#import "PingLunOnZiXunTableViewCell.h"
#import "AFNetworking.h"
#import "MJRefresh.h"

#define kCurrentUserToken [[NSUserDefaults standardUserDefaults]objectForKey:@"token"]

@interface PingListViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *allPingLunTableView;

@property (nonatomic, strong) NSMutableArray *allPingLunDataArray; // 所有评论的数组

@property (nonatomic, assign) NSInteger pingLunCount; // 评论的数量

@property (nonatomic, assign) NSInteger dianZanCount; // 点赞的数量

@property (nonatomic, assign) __block BOOL pingLunShiFouKeYiDianZan; // 是否可以对评论点赞，默认为可以

@property (nonatomic, assign) __block BOOL canClickLaJiTong; // 是否可以点击垃圾桶,默认为可以

@end

@implementation PingListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    // navi的修改
    [self changeNavigation];
    // 布局
    [self addMySubview];
    // 是否可以点击评论、是否可以点击垃圾桶
    self.pingLunShiFouKeYiDianZan = YES;
    self.canClickLaJiTong = YES;
}

// navi的修改
- (void)changeNavigation
{
    self.navigationItem.title = @"所有评论";
    UIImageView *leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    leftImageView.image = [UIImage imageNamed:@"houtui"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftImageView];
    UITapGestureRecognizer *leftTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lastPage:)];
    [leftImageView addGestureRecognizer:leftTapGes];
    
}

#pragma mark - 返回上一页面
- (void)lastPage:(UITapGestureRecognizer *)tapGes
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 添加数据源
- (void)addData
{
    self.pingLunCount = 0;
    
    self.pingLunCount = self.allPingLunDataArray.count;
    [self.allPingLunTableView.header endRefreshing]; 
    [self.allPingLunTableView reloadData];
    
}

#pragma mark - 布局
- (void)addMySubview
{
    self.allPingLunTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
    self.allPingLunTableView.backgroundColor = [UIColor whiteColor];
    self.allPingLunTableView.dataSource = self;
    self.allPingLunTableView.delegate = self;
    [self.view addSubview:_allPingLunTableView];
    
    // 无用的下拉刷新，给用户的错觉，因为这个界面的数据没办法在这个界面请求
    self.allPingLunTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 添加数据源
        [self addData];
    }];
    [self.allPingLunTableView.header beginRefreshing];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.allPingLunDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"userPingLunCell";
    PingLunOnZiXunTableViewCell *pingLunOnZiXunCell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (pingLunOnZiXunCell == nil) {
        pingLunOnZiXunCell = [[PingLunOnZiXunTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    if (self.allPingLunDataArray.count > indexPath.row) {
        pingLunOnZiXunCell.model = self.allPingLunDataArray[indexPath.row];
    }
    UITapGestureRecognizer *dianZanTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dianZanGes:)];
    [pingLunOnZiXunCell.dianZanImageV addGestureRecognizer:dianZanTapGes];
    pingLunOnZiXunCell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    UITapGestureRecognizer *shanChuPingLunTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(shanChuPingLunGes:)];
    [pingLunOnZiXunCell.laJiTongImageV addGestureRecognizer:shanChuPingLunTapGes];
    return pingLunOnZiXunCell;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 39 * kAdjustParamater)];
    headView.backgroundColor = [UIColor whiteColor];
    // 评论label
    UILabel *pingLunLabel = [[UILabel alloc] initWithFrame:CGRectMake(25 * kAdjustParamater, 12 * kAdjustParamater, 100 * kAdjustParamater, 14 * kAdjustParamater)];
  //  pingLunLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];
    
    pingLunLabel.text = [NSString stringWithFormat:@"评论%ld", self.pingLunCount];
    pingLunLabel.textColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
    pingLunLabel.textAlignment = NSTextAlignmentLeft;
    pingLunLabel.font = [UIFont systemFontOfSize:k14Big];
    [headView addSubview:pingLunLabel];
    
    // 点赞人数
    UILabel *dianZanLabel = [[UILabel alloc] initWithFrame:CGRectMake((375 - 25 - 100) * kAdjustParamater, 12 * kAdjustParamater, 100 * kAdjustParamater, 14 * kAdjustParamater)];
   // dianZanLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];
    self.dianZanCount = 0;
    self.allPingLunDataArray = [NSMutableArray arrayWithArray:self.pingLunArray];
    for (int i = 0; i < self.allPingLunDataArray.count; i++) {
        ZiXunGeRenPingLunModel *model = self.allPingLunDataArray[i];
        // 点赞人数
        NSInteger likeNum = [model.like_num integerValue];
        self.dianZanCount = self.dianZanCount + likeNum;
    }
    dianZanLabel.text = [NSString stringWithFormat:@"赞%ld", self.dianZanCount];
    dianZanLabel.textColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
    dianZanLabel.textAlignment = NSTextAlignmentRight;
    dianZanLabel.font = [UIFont systemFontOfSize:k14Big];
    [headView addSubview:dianZanLabel];
    
    // 底部灰色条
    UILabel *grayLineOnBottom = [[UILabel alloc] initWithFrame:CGRectMake(0, 38 * kAdjustParamater, kScreenWidth, 1 * kAdjustParamater)];
    grayLineOnBottom.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.08];
    [headView addSubview:grayLineOnBottom];
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 39 * kAdjustParamater;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
   // 动态返回高度
    PingLunOnZiXunTableViewCell *pingLunCell = (PingLunOnZiXunTableViewCell *)[self tableView:self.allPingLunTableView cellForRowAtIndexPath:indexPath];
    return pingLunCell.grayBackGroundView.bottom + 12 * kAdjustParamater;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 20 * kAdjustParamater)];
    footerView.backgroundColor = [UIColor whiteColor];
    return footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 20 * kAdjustParamater;
}

#pragma mark - 对发表的评论进行点击
- (void)dianZanGes:(UITapGestureRecognizer *)tapGes
{
    // 防止点赞多次点击
    if (self.pingLunShiFouKeYiDianZan == YES) {
        self.pingLunShiFouKeYiDianZan = NO;
        UIView *contentV = [tapGes.view superview];
        PingLunOnZiXunTableViewCell *cell = (PingLunOnZiXunTableViewCell *)[contentV superview];
        NSIndexPath *tempIndexPath = [self.allPingLunTableView indexPathForCell:cell];
        NSLog(@"对%ld进行点赞", tempIndexPath.row);
        if (self.allPingLunDataArray.count > tempIndexPath.row) {
            ZiXunGeRenPingLunModel *model = self.allPingLunDataArray[tempIndexPath.row];
            // 当前用户是否喜欢
            NSString *currentUserIsLike = [NSString stringWithFormat:@"%@", model.is_liked];
            NSString *newscomment_idString = [NSString stringWithFormat:@"%@", model.myUserID];
            __block NSInteger likeNum = [model.like_num integerValue];
            if ([currentUserIsLike isEqualToString:@"0"]) {
                // 说明不喜欢，想要喜欢
                NSString *urlString = [NSString stringWithFormat:@"http://120.26.129.84/api/news/commentlike?token=%@", kCurrentUserToken];
                NSDictionary *paramaterDic = @{@"newscomment_id": newscomment_idString};
                AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                [manager POST:urlString parameters:paramaterDic success:^(NSURLSessionDataTask *task, id responseObject) {
                    if (!responseObject) {
                        return;
                    }
                    NSDictionary *statusDic = [responseObject valueForKey:@"status"];
                    if ([[statusDic valueForKey:@"msg"] isEqualToString:@"点赞成功"]) {
                        NSLog(@"点赞成功");
                        model.is_liked = @"1";
                        likeNum++;
                        model.like_num = [NSString stringWithFormat:@"%ld", likeNum];
                        [self.allPingLunTableView reloadData];
                        cell.dianZanImageV.image = [UIImage imageNamed:@"dianzanguole-zixun"];
                    }
                    // 开启点赞
                    self.pingLunShiFouKeYiDianZan = YES;
                } failure:^(NSURLSessionDataTask *task, NSError *error) {
                    // 开启点赞
                    self.pingLunShiFouKeYiDianZan = YES;
                }];
            } else if ([currentUserIsLike isEqualToString:@"1"]) {
                // 说明喜欢，想要不喜欢
                NSString *urlString = [NSString stringWithFormat:@"http://120.26.129.84/api/news/commentlike?token=%@", kCurrentUserToken];
                NSDictionary *paramaterDic = @{@"newscomment_id": newscomment_idString};
                AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                [manager DELETE:urlString parameters:paramaterDic success:^(NSURLSessionDataTask *task, id responseObject) {
                    if (!responseObject) {
                        return;
                    }
                    NSDictionary *statusDic = [responseObject valueForKey:@"status"];
                    if ([[statusDic valueForKey:@"msg"] isEqualToString:@"取消成功"]) {
                        NSLog(@"取消成功");
                        model.is_liked = @"0";
                        likeNum--;
                        model.like_num = [NSString stringWithFormat:@"%ld", likeNum];
                        [self.allPingLunTableView reloadData];
                        cell.dianZanImageV.image = [UIImage imageNamed:@"weidianzan-zixun"];
                    }
                    // 开启点赞
                    self.pingLunShiFouKeYiDianZan = YES;
                } failure:^(NSURLSessionDataTask *task, NSError *error) {
                    // 开启点赞
                    self.pingLunShiFouKeYiDianZan = YES;
                }];
            }
            // model数值发生变化，进行model的回调
            self.rowOfModel(model, tempIndexPath.row);
        }
    }
    
}

#pragma mark - 点击垃圾桶
- (void)shanChuPingLunGes:(UITapGestureRecognizer *)tapGes
{
    UIView *contentV = [tapGes.view superview];
    PingLunOnZiXunTableViewCell *cell = (PingLunOnZiXunTableViewCell *)[contentV superview];
    NSIndexPath *tempIndexPath = [self.allPingLunTableView indexPathForCell:cell];
    [self addAlert:@"您确定要删除该评论么" IndexPath:tempIndexPath];
}

#pragma mark - 提醒框
- (void)addAlert:(NSString *)content IndexPath:(NSIndexPath *)indexPath
{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"警告" message:content preferredStyle:UIAlertControllerStyleAlert];
    // 修改标题颜色
    NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:@"警告"];
    [title addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 2)];
    [title addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(0, 2)];
    [alertVC setValue:title forKey:@"attributedTitle"];
    
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //   NSLog(@"确定");
        // 防止多次点击
        if (self.canClickLaJiTong == YES) {
            self.canClickLaJiTong = NO;
            NSString *urlString = [NSString stringWithFormat:@"http://120.26.129.84/api/news/comment?token=%@", kCurrentUserToken];
            if (self.allPingLunDataArray.count > indexPath.row) {
                ZiXunGeRenPingLunModel *model = self.allPingLunDataArray[indexPath.row];
                
                NSString *pingLunID = [NSString stringWithFormat:@"%@", model.myUserID];
                NSDictionary *paramaterDic = @{@"newscomment_id":pingLunID};
                AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                [manager DELETE:urlString parameters:paramaterDic success:^(NSURLSessionDataTask *task, id responseObject) {
                    NSDictionary *statusDic = [responseObject valueForKey:@"status"];
                    NSString *msgString = [statusDic valueForKey:@"msg"];
                    if ([msgString isEqualToString:@"删除成功"]) {
                        NSLog(@"删除成功");
                        // 删除对应的数据
                        [self.allPingLunDataArray removeObjectAtIndex:indexPath.row];
                        [self.allPingLunTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
                        // block回调删除对应航
                        self.deleteRow(indexPath.row);
                        //  [self.allPingLunTableView reloadData];
                    }
                    // 开启垃圾桶点击
                    self.canClickLaJiTong = YES;
                } failure:^(NSURLSessionDataTask *task, NSError *error) {
                    NSLog(@"错误error = %@", error);
                    // 开启垃圾桶点击
                    self.canClickLaJiTong = YES;
                }];
            }

        }
        
    }];
    [alertVC addAction:sureAction];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVC addAction:cancelAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
